<script setup>
import {onMounted, ref} from 'vue'
import {ElButton, ElMessage, ElMessageBox} from 'element-plus'
import msgApi from "../api/msgApi.js";

const msgs = ref([])

loadMsg()
async function loadMsg(){
  console.log("等待消息")
  while (true) {
    try {
      const resp = await msgApi.getMsg()
      // 将消息添加到msgs数组中
      if (resp.code===200) {
        msgs.value=resp.data
      }
    } catch (error) {
      console.error("长轮询错误", error)
    }
    await new Promise(resolve => setTimeout(resolve, 10000))
  }
}
function del(msgId){
  if (confirm("确定要删除吗")){
    msgApi.delete(msgId).then(resp=>{
      loadMsg()
    })
  }
}
function changeStatus(msgId,status){
  if (status===1){
    console.log(msgId,status)
    msgApi.changeStatus(msgId).then(resp=>{
      loadMsg()
    })
  }
}
</script>

<template>
  <div>
    <p>消息列表</p>
    <p v-if="msgs.length === 0">暂无消息</p>
    <el-card @click="changeStatus(msg.msgId,msg.status)" style="max-width: 480px" v-for="(msg,index) in msgs"
      >
      <p>课程名：{{msg.name}}</p>
      <p>上课时间：{{msg.time}}</p>
      <p>上课时长：{{msg.length}}</p>
      <p>上课教室：{{msg.roomName}}</p>
      <p>状态：{{msg.status===1?'未读':'已读'}}</p>
      <el-button type="danger" @click="del(msg.msgId)">删除</el-button>
    </el-card>
  </div>
</template>

<style scoped>
div{
  margin-top: -50px;
}
.el-card{
  margin: 0;
  background-color: gray;
}
</style>
